$(function(){

    $(".box tr:last").find("td").css('border-bottom' , 'none');

    $(".step2").click(function(){
        if ( !validate() ) { return false; }
        var date = $( "form" ).serialize();
        var url = weburl + "/install/?a=checkDB";
        var obj = $( this );
        setButton( obj );
        $.post( url, date, function ( result ) {
            if ( result == 'success' ) {
                $( "form" ).submit();
                return;
            }
            if ( result == 'unique' ) {
                if ( confirm( '当前数据库当中已经含有同样表前缀的数据表。\n您可以修改“表前缀”来避免删除旧的数据。\n继续安装会清空所有记录!' ) ) {
                    $( "form" ).submit();
                }
                return;
            }
            obj.after( "<span>" + result + "</span>" );
            window.setTimeout( function () { setButton( obj, 1 ); obj.next( "span" ).remove(); }, 4000 );
            return false;
        });
        return false;
    });

    $(".step3").click(function(){
        var obj = $(this);
        if ( !validate() ) { return false; }
        if ( !check_equal( 'user[pass]', 'user[pass1]' ) ) {
            setButton( obj );
            obj.next( "span" ).remove();
            obj.after( "<span>2次密码不一样!</span>" );
            $( 'input[name="user[pass]"]' ).focus();
            window.setTimeout( function () { setButton( obj, 1 ); obj.next( "span" ).remove(); }, 3000 ); return false;
        }
        $( "form" ).submit();
    });
});

function check_equal(a ,b){
    var aa = $( 'input[name="' + a + '"]' ).val();
    var bb = $( 'input[name="' + b + '"]' ).val();
    aa = $.trim( aa );
    bb = $.trim( bb );
    return aa == bb;
}

function install( debug ){
    var obj = $(".button");
    setButton( obj );
    var url = $("form").attr('action');
    var date = $("form").serialize();
    var t = null;
    var i = 0;

    if( debug ){
        $("form" ).submit();return;
    }

    $.post( url, date, function( result ){
        var tmp = result.split("<br />");
        var len = tmp.length - 1;
        $('#notice').fadeIn( 1000 );
        if ( result.indexOf( 'Fatal error' ) != -1 || result.indexOf( '错误提示' ) != -1 ) {
            $( "#notice" ).html( result );
            return;
        }
        t = window.setInterval( function () {
            i++;
            if ( i >= len ) {
                window.clearInterval( t );
                obj.val( '安装完成...' );
                window.setTimeout( function () { window.location = obj.attr( 'href' ); }, 2000 );
            }
            if ( tmp[i] ) { $( "#notice" ).append( tmp[i] + "<br />" );  }
        }, 300 );
    });
}
